package org.example.studentteacherassignmentsystem.controller;

import jakarta.validation.Valid;
import org.example.studentteacherassignmentsystem.model.Student;
import org.example.studentteacherassignmentsystem.model.Teacher;
import org.example.studentteacherassignmentsystem.repository.TeacherRepository;
import org.example.studentteacherassignmentsystem.repository.StudentRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;


@Controller
public class TeacherController {
    @Autowired
    private TeacherRepository teacherRepository;
    @Autowired
    private StudentRepository studentRepository;

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("teachers", teacherRepository.findAll());
        return "index";
    }

    @GetMapping("/newTeacher")
    public String showTeacherForm(Model model) {
        model.addAttribute("teacher", new Teacher());
        return "teacherForm";
    }

    @PostMapping("/saveTeacher")
    public String saveTeacher(
            @Valid @ModelAttribute Teacher teacher,  // 添加 @Valid
            BindingResult result,                   // 添加 BindingResult
            Model model) {
        if (result.hasErrors()) {
            return "teacherForm";  // 验证失败时返回表单页面
        }
        teacherRepository.save(teacher);
        return "redirect:/";
    }
    @GetMapping("/assignStudents")
    public String showAssignStudents(@RequestParam Long id, Model model) {
        Teacher teacher = teacherRepository.findById(id).orElseThrow();
        model.addAttribute("teacher", teacher);
        model.addAttribute("assignedStudents", studentRepository.findByTeacher(teacher));
        model.addAttribute("unassignedStudents", studentRepository.findByTeacherIsNull());
        return "assignStudents";
    }

    @GetMapping("/assignStudent")
    public String assignStudent(@RequestParam Long studentId, @RequestParam Long teacherId) {
        Student student = studentRepository.findById(studentId).orElseThrow();
        Teacher teacher = teacherRepository.findById(teacherId).orElseThrow();
        student.setTeacher(teacher);
        studentRepository.save(student);
        return "redirect:/assignStudents?id=" + teacherId;
    }

    @GetMapping("/uploadPhoto")
    public String showUploadForm(@RequestParam Long id, @RequestParam Long teacherId, Model model) {
        model.addAttribute("studentId", id);
        model.addAttribute("teacherId", teacherId);
        return "uploadPhoto";
    }

    @Value("${file.upload-dir}")
    private String uploadDir;

    @PostMapping("/uploadPhoto")
    public String handleFileUpload(
            @RequestParam Long studentId,
            @RequestParam Long teacherId,
            @RequestParam("file") MultipartFile file) throws IOException {

        if (!file.isEmpty()) {
            // 获取项目根目录路径
            Path uploadPath = Paths.get(uploadDir).toAbsolutePath().normalize();

            // 确保目录存在
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成唯一文件名
            String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
            Path filePath = uploadPath.resolve(fileName);

            // 保存文件
            file.transferTo(filePath);

            // 更新数据库（存储相对路径）
            Student student = studentRepository.findById(studentId).orElseThrow();
            student.setPhoto("/uploads/" + fileName);
            studentRepository.save(student);
        }

        return "redirect:/assignStudents?id=" + teacherId;
    }
}